import Vue from 'vue';
import Broadcast from '@/tools/broadcast.js';
import states from '@/store/state.js';
// import login from '@/api/login.js';
import types from '@/constants/types';
import indexJs from '@/store/index.js';
import router from '@/router/index.js';
import {
    Message
} from 'element-ui';

function mySocket() {
    this.socket = null;
    this.open = function() {
        if (!states.studentsState.serverUrl) {
            console.log('未获取serverUrl')
            return;
        }
        let wsUri = states.studentsState.serverUrl;
        let socket = new WebSocket(wsUri);
        socket.onopen = this.onSocketOpen;
        socket.onerror = this.onSocketError;
        socket.onmessage = this.onSocketMessage;
        socket.onclose = this.onSocketclose;
        this.socket = socket;
    }
    this.close = function() {
        if (this.socket) {
            this.socket.close()
            this.socket = null;
            console.log("关闭socket");
        }
    }

    this.onSocketOpen = function() {
        console.log(states);
        sessionStorage.setItem("chatHistory", JSON.stringify([]))
        indexJs.commit(types.CHATSTORYLIST, []);
        console.log("WebSocket连接成功", this);
    }
    this.onSocketError = function(e) { //错误
        console.log("WebSocket连接发生错误", e);
    }
    this.onSocketclose = function(e) {
        console.log("WebSocket断开连接,e", e);
    }
    this.onSocketMessage = function(e) {
        console.log("WebSocket接收消息", e);
        let val = JSON.parse(JSON.parse(e.data));
        switch (val.messageType) {
            case 'chat':
                let arr = JSON.parse(sessionStorage.getItem("chatHistory"));
                arr.push(val.content)
                sessionStorage.setItem("chatHistory", JSON.stringify(arr));
                indexJs.commit(types.CHATSTORYLIST, arr);
                break;
            case 'function':
                if (val.content.refresh) refresh(val.content.refresh); //如果功能为刷新列表时调用
                if (val.content.type == "createRoom") {
                    createRoom(val.content.createRoom);
                }
                if (val.content.type == "joinRoom") {
                    joinRoom(val.content.joinRoom);
                }
                if (val.content.type == "exitRoom") {
                    exitRoom(val.content.exitRoom);
                }
                if (val.content.type == "updateready") {
                    updateready(val.content.updateready);
                }
                if (val.content.type == "checkRoom") {
                    checkRoom(val.content.checkRoom);
                }
                if (val.content.type == "gotest") {
                    gotest(val.content.gotest);
                }
                if (val.content.type == "deleteRoom") {
                    deleteRoom(val.content.deleteRoom);
                }
                break;
            case 'topicAnswered':
                Broadcast.emit('topicAnswered', val.content)
                break;
            case 'accountEntryStatus':
                Broadcast.emit('accountEntryStatus', val.content)
                break;
            case 'bigDataAnalyst':
                indexJs.commit(`students/${types.BIGDATAANALYST}`);
                break;
            case 'examSubmit':
                let {
                    positionId
                } = val.content;
                let positionList = indexJs.state.getExamPaperPositions;
                let curPositionId = indexJs.state.students.positionId;
                let targetPosition = positionList.Data.find(pos => pos.PostionId == positionId);
                let targetPosName = targetPosition.PostionName;
                if (targetPosName.indexOf('大数据') > -1) {
                    indexJs.commit(`students/${types.BIGDATAANALYST}`);
                }
                Broadcast.emit('examSubmit', {
                    positionId,
                    curPositionId,
                    targetPosName
                });
                break;
            case 'heartBeat':
                Broadcast.emit('heartBeat');
                break;
            case 'examEnded':
                let pathStr = router.currentRoute.path;
                let query = router.currentRoute.query
                if (pathStr.includes('/selfInnerRaceTopic/index')) { //个人赛
                    router.push({
                        path: '/InnerRace/screen',
                        query: JSON.parse(query.query)
                    })
                } else if (pathStr.includes('InnerRaceTopic')) { //校内赛
                    router.push({
                        path: "/innerRace"
                    });
                } else if (pathStr.includes('/topic/index')) { //模拟训练
                    router.push({
                        path: "/simulatedTraining"
                    });
                } else {
                    router.go(-1);
                }
                break;
        }
    }
    this.onSend = function(e) { //像消息服务器发送消息
        console.log(e);
        login.sendgroupmsg(e);
    }
    this.joingroup = function(groupId) { //加入群聊
        login.joingroup({
            groupId: groupId * 1,
        }).then(res => {

            if (res.Code == 200) {
                console.log("加入群聊！")
            } else {
                console.log("fail")
                    // Notification.info({
                    //     title: "提示",
                    //     message: '加入群聊失败',
                    // });
            }
        });
    }
    this.leavegroup = function(groupId) { //退出群聊
            login.leavegroup({
                groupId: groupId * 1,
            }).then(res => {

                if (res.Code == 200) {
                    console.log("离开群聊成功！")
                } else {
                    // Notification.info({
                    //     title: "提示",
                    //     message: "离开群聊失败",
                    // });
                }
            });
        }
        // 创建房间方法
    var createRoom = function(e) {
            console.log(states.rootState);
            let arr = JSON.parse(JSON.stringify(states.rootState.getExamPaperGroupListByPage));
            if (e.CreateBy == states.rootState.students.loginData.Id) {
                arr.Data.unshift(e);
            } else {
                arr.Data.push(e);
            }
            indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, arr);
        }
        //加入房间
    var joinRoom = function(e) {
            console.log(e, states.rootState.getExamPaperGroupListByPage)
            let arr = JSON.parse(JSON.stringify(states.rootState.getExamPaperGroupListByPage));
            for (var i = arr.Data.length; i--;) {
                if (arr.Data[i].GroupId == e.GroupId) {
                    arr.Data[i].ExamPaperGroupStudentList.push(e);
                    if (arr.Data[i].ExamPaperGroupStudentList.length == 4) {
                        arr.Data[i].Status = 1;
                    }
                }
            }
            indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, arr);
        }
        // 退出房间
    var exitRoom = function(e) {
            console.log(e, states.rootState.getExamPaperGroupListByPage);
            let arr = JSON.parse(JSON.stringify(states.rootState.getExamPaperGroupListByPage));
            for (var i = arr.Data.length; i--;) {
                if (arr.Data[i].CreateBy == e.UserId) {
                    arr.Data.splice(i, 1);
                    break;
                }
                if (arr.Data[i].GroupId == e.GroupId) {
                    for (var j = arr.Data[i].ExamPaperGroupStudentList.length; j--;) {
                        if (e.UserId == arr.Data[i].ExamPaperGroupStudentList[j].UserId) {
                            console.log(arr.Data[i].ExamPaperGroupStudentList);
                            arr.Data[i].ExamPaperGroupStudentList.splice(j, 1);
                            arr.Data[i].Status = 0;
                        }
                    }
                }
            }
            indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, arr);
        }
        //进入准备状态、取消准备状态
    var updateready = function(e) {
            console.log(e, states.rootState.getExamPaperGroupListByPage);
            let arr = JSON.parse(JSON.stringify(states.rootState.getExamPaperGroupListByPage));
            for (var i = arr.Data.length; i--;) {
                if (arr.Data[i].GroupId == e.GroupId) {
                    let str = "";
                    for (var j = arr.Data[i].ExamPaperGroupStudentList.length; j--;) {
                        if (e.UserId == arr.Data[i].ExamPaperGroupStudentList[j].UserId) {
                            arr.Data[i].ExamPaperGroupStudentList[j].IsReady = e.IsReady;
                        }
                        if (arr.Data[i].ExamPaperGroupStudentList.length == 4) {
                            str += arr.Data[i].ExamPaperGroupStudentList[j].IsReady;
                        }
                    }
                    if (str == "truetruetruetrue") {
                        arr.Data[i].Status = 2;
                    } else {
                        arr.Data[i].Status = 1;
                    }
                }
            }
            indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, arr);
        }
        //切换岗位
    var checkRoom = function(e) {
            let arr = JSON.parse(JSON.stringify(states.rootState.getExamPaperGroupListByPage));
            console.log(arr);
            for (let i = arr.Data.length; i--;) {
                for (let j = arr.Data[i].ExamPaperGroupStudentList.length; j--;) {
                    if (e.UserId == arr.Data[i].ExamPaperGroupStudentList[j].UserId) {
                        arr.Data[i].ExamPaperGroupStudentList[j].PostionId = e.PostionId
                        arr.Data[i].ExamPaperGroupStudentList[j].PostionName = e.PostionName
                    }
                }
            }
            indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, arr);
        }
        //进入考试
    var gotest = function(e) {
            console.log(e, states.rootState.getExamPaperGroupListByPage);
            let arr = JSON.parse(JSON.stringify(states.rootState.getExamPaperGroupListByPage));
            for (var i = arr.Data.length; i--;) {
                if (arr.Data[i].GroupId == e.GroupId) {
                    arr.Data[i].Status = 3;
                }
            }
            indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, arr);
        }
        //四人桌最后一人交卷后所有人清除该桌子
    var deleteRoom = function(e) {
            console.log(e, states.rootState.getExamPaperGroupListByPage);
            let arr = JSON.parse(JSON.stringify(states.rootState.getExamPaperGroupListByPage));
            if (arr.Data) {
                for (var i = arr.Data.length; i--;) {
                    if (arr.Data[i].GroupId == e.GroupId) {
                        arr.Data.splice(i, 1);
                    }
                }
                indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, arr);
            }
        }
        // 刷新列表方法
    var refresh = function(value) {
        console.log(value, types, states, indexJs);
        login.getexampapergrouplistbypage(value.params).then(res => {

            indexJs.commit(types.GETEXAMPAPERGROUPLISTBYPAGE, res);
        }).catch(err => {
            console.log(err)
        })
    }
}
export default new mySocket();